package com.ktjiaoyu.ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;

import java.util.ArrayList;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private final CategoryDao categoryDao=new CategoryDaoImpl();
    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }

    @Override
    public List<Category> findTree() {
        List<Category> all=categoryDao.findAll();
        return buildTree(all,"0");
    }

    @Override
    public boolean removeById(Long id) {
        return categoryDao.delete(id)>0;
    }

    @Override
    public int insert(Category category) {
        return categoryDao.insert(category);
    }

    @Override
    public int update(Category category) {
        return categoryDao.update(category);
    }

    private List<Category> buildTree(List<Category> all,String parentId){
        List<Category> tree=new ArrayList<>();
        for(Category cat:all){
            if(cat.getParentId() !=null && cat.getParentId().equals(parentId)){
                List<Category> children=buildTree(all,cat.getParentId());
                cat.setChildren(children);
                tree.add(cat);
            }
        }
        return tree;
    }
}
